package face.jx.sdk;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import face.jx.sdk.util.Config;
import face.jx.sdk.util.IFaceResultCallBack;
import face.jx.sdk.util.PictureUtil;
import face.jx.sdk.util.StatusBarUtils;


/**
 * 离线视频流检测
 */
public class RegisterFaceActivity extends BaseFaceActivity {
	public static final String KEY_MAX_RECO_COUNT = "KEY_MAX_RECO_COUNT";
	public static final String KEY_HAS_RECO_COUNT = "KEY_HAS_RECO_COUNT";
	private static IFaceResultCallBack iFaceResultCallBack;
	private int maxRecoCount;//最大检测次数
	private int hasRecoCount;//已经检测的次数

	private final static String API_KEY = "lJsij4n8pYEj3bW-tSJqEhRgkdfHobC8";
	private final static String API_Secret = "i1H3kRBBzJ2Wo_1T-6RsbRmWgcHAREww";
	private static int fileUploadProgress = 0;
	private final static String TAG = RegisterFaceActivity.class.getSimpleName();
	private AlertDialog dialog = null;
	private TextView button_take_photos;
	private TextView button_up_photos;
	private TextView tip_take_photo;
	private TextView title_text;
	private ImageView tip_image,imageView_preview;
	private static final int PHOTO_REQUEST_GALLERY = 1;
	private static final int PHOTO_REQUEST_CUT = 2;

	public static void startActivity(Activity activity, int maxRecoCount, int hasRecoCount, IFaceResultCallBack callBack){
		if(activity == null){
			return;
		}
		iFaceResultCallBack = callBack;
		Intent intent = new Intent(activity, RegisterFaceActivity.class);
		intent.putExtra(KEY_MAX_RECO_COUNT,maxRecoCount);
		intent.putExtra(KEY_HAS_RECO_COUNT,hasRecoCount);
		activity.startActivity(intent);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		StatusBarUtils.setWindowStatusBarColor(this,R.color.color_black);
		super.onCreate(savedInstanceState);
		initData();
		initUI();
	}

	private void initData(){
		maxRecoCount = getIntent().getIntExtra(KEY_MAX_RECO_COUNT, Config.DE_MAX_RECOGNITION_COUNT);
		hasRecoCount = getIntent().getIntExtra(KEY_HAS_RECO_COUNT, Config.DE_HAS_RECOGNITION_COUNT);
	}


	@SuppressLint("ShowToast")
	@SuppressWarnings("deprecation")
	private void initUI() {
		tip_image = (ImageView) findViewById(R.id.tip_image);
		imageView_preview = (ImageView) findViewById(R.id.imageView_preview);
		button_take_photos = (TextView) findViewById(R.id.button_take_photos);
		button_up_photos = (TextView) findViewById(R.id.button_up_photos);
		tip_take_photo = (TextView) findViewById(R.id.tip_take_photo);
		title_text = (TextView) findViewById(R.id.title_text);
		button_take_photos.setClickable(true);
		button_take_photos.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!isUpModel){
					button_take_photos.setClickable(false);
					mCamera.takePicture(null, null, jpeg);
				}else{
					changeToReUI();
				}

			}
		});

		button_up_photos.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(hasRecoCount >= maxRecoCount){
					Toast.makeText(RegisterFaceActivity.this,"您已经达到验证次数上限，为您上传照片，后台人员验证", Toast.LENGTH_SHORT).show();

					button_up_photos.postDelayed(new Runnable() {
						@Override
						public void run() {
							if(iFaceResultCallBack!=null){
								iFaceResultCallBack.onFaceRecognitionReult(IFaceResultCallBack.RESULT_CODE_ERR,"照片上传成功，请等待人工审核",hasRecoCount);
								finish();
							}
						}
					},2000);
				}else{
					hasRecoCount++;
					Toast.makeText(RegisterFaceActivity.this,"未完成功能，上传验证。", Toast.LENGTH_SHORT).show();

					button_up_photos.postDelayed(new Runnable() {
						@Override
						public void run() {
							if(iFaceResultCallBack!=null){
								iFaceResultCallBack.onFaceRecognitionReult(IFaceResultCallBack.RESULT_CODE_OK,"恭喜你验证成功",hasRecoCount);
								finish();
							}
						}
					},2000);
				}

			}
		});

		doRecoCount();
	}

	Camera.PictureCallback jpeg = new Camera.PictureCallback() {
		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			Log.i(TAG, "onPictureTaken_data.length: " + data.length);
			String filename = "waitForRename.jpg";
			FileOutputStream fos;
			//获取拍到的图片Bitmap
			Bitmap bitmap_source = null;
			String pictureStoragePath = PictureUtil.getPictureStoragePath(getApplicationContext());
			File f = new File(pictureStoragePath, filename);
			try {
				fos = new FileOutputStream(f);
				if (data.length < 35000) {
					YuvImage image = new YuvImage(nv21, ImageFormat.NV21, PREVIEW_WIDTH, PREVIEW_HEIGHT, null);   //将NV21 data保存成YuvImage
					//图像压缩
					image.compressToJpeg(
							new Rect(0, 0, image.getWidth(), image.getHeight()),
							100, fos);
					Log.i(TAG, "onPictureTaken_data.length<20000: " + data.length);
					Log.i(TAG, "onPictureTaken_nv21.length: " + nv21.length);
					bitmap_source = PictureUtil.compressFacePhoto(f.getAbsolutePath());
					fos = new FileOutputStream(f);
					BufferedOutputStream bos = new BufferedOutputStream(fos);
					//旋转图片
					// 根据旋转角度，生成旋转矩阵
					Matrix matrix = new Matrix();
					if(mCameraId == CameraInfo.CAMERA_FACING_FRONT){
						matrix.postRotate(270);
					}else{
						matrix.postRotate(90);
					}
					//TODO
					Bitmap mBitmap1 = Bitmap.createBitmap(bitmap_source, 0, 0, bitmap_source.getWidth(), bitmap_source.getHeight(), matrix, true);
					boolean result = mBitmap1.compress(Bitmap.CompressFormat.JPEG, 100, bos);
					bos.close();
					Log.i(TAG, "onPictureTaken_mBitmap1.compress: " + result);
				} else {
					bitmap_source = PictureUtil.compressFacePhoto(data);
					BufferedOutputStream bos = new BufferedOutputStream(fos);
					//旋转图片
					// 根据旋转角度，生成旋转矩阵
					Matrix matrix = new Matrix();
					if(mCameraId == CameraInfo.CAMERA_FACING_FRONT){
						matrix.postRotate(270);
					}else{
						matrix.postRotate(90);
					}
					Bitmap mBitmap1 = Bitmap.createBitmap(bitmap_source, 0, 0, bitmap_source.getWidth(), bitmap_source.getHeight(), matrix, true);
					mBitmap1.compress(Bitmap.CompressFormat.JPEG, 70, bos);
					bos.close();
				}
				fos.flush();
				fos.close();

				Log.i(TAG, "onPictureTaken: 图片保存成功");
//				Intent intent = new Intent(getApplicationContext(), DialogInputNameActivity.class);
//				startActivityForResult(intent, 0);
				Toast.makeText(RegisterFaceActivity.this,"图片保存成功，准备上传验证。", Toast.LENGTH_SHORT).show();
			} catch (Exception e) {
				System.out.println("图片保存异常" + e.getMessage());
				e.printStackTrace();
			}

			button_take_photos.setClickable(true);

			changeToUpUI();


		}
	};

	/**
	 * 处理验证次数
	 */
	private void doRecoCount(){
		if(hasRecoCount>=maxRecoCount){
			tip_image.setVisibility(View.GONE);
			tip_take_photo.setVisibility(View.GONE);
			button_up_photos.setText(R.string.man_up_photo_tip);
			title_text.setText(R.string.man_title_text2);
			button_up_photos.postDelayed(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(RegisterFaceActivity.this,"您已达到最大验证次数，请直接拍照上传", Toast.LENGTH_SHORT).show();
				}
			},1000);
		}else{
			tip_image.setVisibility(View.VISIBLE);
			tip_take_photo.setVisibility(View.VISIBLE);
			button_up_photos.setText(R.string.man_up_photo_text);
			title_text.setText(R.string.man_title_text);
		}
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode){
			case PHOTO_REQUEST_GALLERY:
				if(data!=null){
					startPhotoZoom(data.getData());
				}else{
					Log.i("onActivityResult: "," ");
				}
				break;
			case PHOTO_REQUEST_CUT:
				if(data!=null){
					if(data.getParcelableExtra("data") instanceof Bitmap){
						Bitmap bitmap = data.getParcelableExtra("data");
						String pictureStoragePath = PictureUtil.getPictureStoragePath(getApplicationContext());
						File file = new File(pictureStoragePath,"waitForRename.jpg");
						try {
							FileOutputStream fos = new FileOutputStream(file);
							imageView_preview.setImageBitmap(bitmap);
							imageView_preview.setVisibility(View.VISIBLE);
							bitmap.compress(Bitmap.CompressFormat.JPEG,80,fos);
							fos.flush();
							fos.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
						Log.i(TAG, "onPictureTaken: 图片保存成功");
//						Intent intent = new Intent(getApplicationContext(), DialogInputNameActivity.class);
//						startActivityForResult(intent, 0);

						Toast.makeText(RegisterFaceActivity.this,"图片保存成功，准备上传验证。", Toast.LENGTH_SHORT).show();

					}else{
						Log.i("onActivityResult: ","false");
					}
				}
				break;
			case 0:
				String username = null;
				String pictureStoragePath = PictureUtil.getPictureStoragePath(getApplicationContext());
				if (data != null) {
					username = data.getStringExtra("username");
				}
				if (resultCode == 1) {
					File file = new File(pictureStoragePath, "waitForRename.jpg");
					if (file.exists()) {
						showNormalDialog(null, "正在注册新人脸，请保持网络通畅...", false, new ProgressBar(this), false);
//						RegisterFace(file, username);
					} else {
						imageView_preview.setVisibility(View.GONE);
						Toast.makeText(this, "错误代码-1，拍照文件保存失败，请检查磁盘空间！", Toast.LENGTH_LONG).show();
					}
					//mCamera.startPreview();//保存之后返回预览界面
				} else {
					File file = new File(pictureStoragePath + "/waitForRename.jpg");
					if (file.exists()) {
						if (file.delete()) {
							Toast.makeText(this, "已取消保存人脸", Toast.LENGTH_LONG).show();
							initUI();
							mCameraId = CameraInfo.CAMERA_FACING_FRONT;
							openCamera();
							mCamera.startPreview();
						} else {

							Toast.makeText(this, "请检查磁盘空间，人脸删除失败", Toast.LENGTH_LONG).show();
						}
					}
					imageView_preview.setVisibility(View.GONE);
				}
				break;
			default:
				break;
		}

	}

	private void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// crop为true是设置在开启的intent中设置显示的view可以剪裁
		intent.putExtra("crop", "true");

		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 3);
		intent.putExtra("aspectY", 4);

		// outputX,outputY 是剪裁图片的宽高
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 400);
		intent.putExtra("return-data", true);
		intent.putExtra("noFaceDetection", true);

		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}


	@Override
	protected void onResume() {
		super.onResume();
		button_take_photos.setClickable(true);
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private void showNormalDialog(String title, String message, boolean cancel, View v, boolean haveButton) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setCancelable(cancel);
		if (title != null) {
			builder.setTitle(title);
		} else {
			builder.setTitle("温馨提示");
		}
		builder.setMessage(message);
		if (v != null) {
			builder.setView(v);
		}
		if (haveButton) {
			builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialogInterface, int i) {
					dialog.dismiss();
					finish();
				}
			});
		}
		dialog = builder.show();
	}

	/**
	 * 转变成预览模式
	 */
	private void changeToReUI(){
		isUpModel = false;
		button_take_photos.setText(R.string.man_tacke_photo_text);
		button_up_photos.setVisibility(View.GONE);
		openCamera();
		mCamera.startPreview();
	}

	private boolean isUpModel = false;
	/**
	 * 转变成上传模式
	 */
	private void changeToUpUI(){
		isUpModel = true;
		button_take_photos.setText(R.string.man_re_tacke_photo_text);
		button_up_photos.setVisibility(View.VISIBLE);
	}

}

